package com.deyou.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.deyou.Constants;
import com.deyou.R;
import com.deyou.base.BaseActivity;
import com.deyou.callback.ServerApi;
import com.deyou.model.HouseResourceDetailBean;
import com.deyou.model.LzyResponse;
import com.deyou.model.PayInfoBean;
import com.deyou.util.AESUtil;
import com.deyou.util.AndroidUtils;
import com.deyou.util.DateUtil;
import com.deyou.util.GlideImageLoader;
import com.deyou.util.SPUtils;
import com.deyou.util.Urls;
import com.google.gson.jpush.reflect.TypeToken;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Type;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

public class ConsultOrBookInfoActivity extends BaseActivity {

    @BindView(R.id.iv_left_back)
    ImageView ivLeftBack;
    @BindView(R.id.tv_mid_title)
    TextView tvMidTitle;
    @BindView(R.id.iv_house)
    ImageView ivHouse;
    @BindView(R.id.tv_house_intro)
    TextView tvHouseIntro;
    @BindView(R.id.tv_house_rental_mode)
    TextView tvHouseRentalMode;
    @BindView(R.id.tv_rent_price)
    TextView tvRentPrice;
    @BindView(R.id.tv_checkin_date)
    TextView tvCheckinDate;
    @BindView(R.id.checkin_date_layout)
    LinearLayout checkinDateLayout;
    @BindView(R.id.tv_checkout_date)
    TextView tvCheckoutDate;
    @BindView(R.id.checkout_date_layout)
    LinearLayout checkoutDateLayout;
    @BindView(R.id.btn_add)
    ImageView btnAdd;
    @BindView(R.id.tv_people_count)
    TextView tvPeopleCount;
    @BindView(R.id.btn_reduce)
    ImageView btnReduce;
    @BindView(R.id.bottom_view)
    TextView bottomView;

    private HouseResourceDetailBean detailBean;
    private int btnType = 0; // 1为联系房东  2为立即预定
    private int checkinPeoPles = 0;
    private String checkInDate, checkOutDate;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_consult_or_book_info);
        ButterKnife.bind(this);
        initData();
        initView();
    }

    private void initData() {
        detailBean = (HouseResourceDetailBean) getIntent().getExtras().getSerializable("houseDetail");
        btnType = getIntent().getExtras().getInt("btnType");

        if (TextUtils.isEmpty(checkInDate))
            checkInDate = DateUtil.getToday("yyyy-MM-dd");
        if (TextUtils.isEmpty(checkOutDate))
            checkOutDate = DateUtil.getTomorry("yyyy-MM-dd");
    }

    private void initView() {
        if (null == detailBean)
            return;
        if (btnType == 1) {
            bottomView.setBackgroundColor(getResources().getColor(R.color.color_005EAD));
            bottomView.setText("联系房东");
            tvMidTitle.setText("联系房东");
            bottomView.setVisibility(View.VISIBLE);
        } else if (btnType == 2) {
            bottomView.setBackgroundColor(getResources().getColor(R.color.color_FF832D));
            bottomView.setText("立即预订");
            tvMidTitle.setText("立即预订");
            bottomView.setVisibility(View.VISIBLE);
        } else {
            bottomView.setVisibility(View.GONE);
        }

        if (null != detailBean.picList && null != detailBean.picList.get(0) && !TextUtils.isEmpty(detailBean.picList.get(0).resourcePic)) {
            new GlideImageLoader().displayImage(this, Urls.HouseResourceImageBaseUrl + detailBean.picList.get(0).resourcePic, ivHouse);
        } else {
            new GlideImageLoader().displayImage(this, R.drawable.img_default, ivHouse);
        }
        tvHouseIntro.setText(detailBean.resourceName);
        tvHouseRentalMode.setText(detailBean.resourceTypeName + "-" + detailBean.resourceRentaltypeName);
        tvRentPrice.setText(Constants.RMB_UNIT + detailBean.resourcePrice);

        tvCheckinDate.setText(checkInDate);
        tvCheckoutDate.setText(checkOutDate);
    }

    @OnClick({R.id.iv_left_back, R.id.checkin_date_layout, R.id.checkout_date_layout, R.id.btn_add, R.id.btn_reduce, R.id.bottom_view, R.id.house_detail_item})
    public void onViewClicked(View view) {
        Bundle bundle = new Bundle();
        switch (view.getId()) {
            case R.id.iv_left_back:
                finish();
                break;
            case R.id.checkin_date_layout:
                bundle.putString("check_in_date", checkInDate);
                bundle.putString("check_out_date", checkOutDate);
                bundle.putInt("selectedType", 1);
                AndroidUtils.startNextActivityForResult(ConsultOrBookInfoActivity.this, SelectHotelDuaActivity.class, bundle, 10101);
                break;
            case R.id.checkout_date_layout:
                bundle.putString("check_in_date", checkInDate);
                bundle.putString("check_out_date", checkOutDate);
                bundle.putInt("selectedType", 2);
                AndroidUtils.startNextActivityForResult(ConsultOrBookInfoActivity.this, SelectHotelDuaActivity.class, bundle, 10101);
                break;
            case R.id.btn_add:
                if (checkinPeoPles >= detailBean.resourceMaximumNum) {
                } else {
                    checkinPeoPles += 1;
                }
                tvPeopleCount.setText(checkinPeoPles + "");
                break;
            case R.id.btn_reduce:
                if (checkinPeoPles <= 0) {
                } else {
                    checkinPeoPles -= 1;
                }
                tvPeopleCount.setText(checkinPeoPles + "");
                break;
            case R.id.bottom_view:
                if (TextUtils.isEmpty(tvPeopleCount.getText()) || Integer.valueOf(tvPeopleCount.getText().toString()) <= 0) {
                    showToast("请先确定入住人数");
                    return;
                }
                if (btnType == 1) {
                    bundle.putString("check_in_date", checkInDate);
                    bundle.putString("check_out_date", checkOutDate);
                    bundle.putSerializable("houseDetail", detailBean);
                    bundle.putInt("stayPeople", Integer.valueOf(tvPeopleCount.getText().toString()));
                    AndroidUtils.startNextActivity(ConsultOrBookInfoActivity.this, ChatWithLandloadActivity.class, bundle, false);
                } else {
                    createOrder();
                }
                break;
            case R.id.house_detail_item:
                bundle.putString("resourceCode", detailBean.resourceId);
                AndroidUtils.startNextActivity(ConsultOrBookInfoActivity.this, HouseResourceDetailActivity.class, bundle, false);
                break;
        }
    }

    private void createOrder() {
        long days = (DateUtil.string2Date10(checkOutDate).getTime() - DateUtil.string2Date10(checkInDate).getTime()) / (1000 * 60 * 60 * 24);
        JSONObject object = new JSONObject();
        try {
            object.put("checkindate", checkInDate);
            object.put("checkoutdate", checkOutDate);
            object.put("resourceId", detailBean.resourceId);
            object.put("orderTitle", detailBean.resourceName);
            object.put("userId", SPUtils.getStringByKey(ConsultOrBookInfoActivity.this, Constants.UserId));
            object.put("checknum", checkinPeoPles);
            object.put("reserveNum", "1");
            object.put("orderAmount", detailBean.resourcePrice * days);
            object.put("customerRemark", "");
            String paramJson = object.toString();

            Type type = new TypeToken<LzyResponse<PayInfoBean>>() {
            }.getType();
            ServerApi.<LzyResponse<PayInfoBean>>getData(type, Urls.createOrder, "", AESUtil.encrypt(paramJson))//
                    .subscribeOn(Schedulers.io())//
                    .doOnSubscribe(new Consumer<Disposable>() {
                        @Override
                        public void accept(@NonNull Disposable disposable) throws Exception {
                            showLoading();
                        }
                    })//
                    .map(new Function<LzyResponse<PayInfoBean>, PayInfoBean>() {
                        @Override
                        public PayInfoBean apply(@NonNull LzyResponse<PayInfoBean> response) throws Exception {
                            return response.data;
                        }
                    })//
                    .observeOn(AndroidSchedulers.mainThread())  //
                    .subscribe(new Observer<PayInfoBean>() {
                        @Override
                        public void onSubscribe(@NonNull Disposable d) {
                            addDisposable(d);
                        }

                        @Override
                        public void onNext(@NonNull PayInfoBean mPayInfo) {
                            Bundle bundle = new Bundle();
//                            bundle.putSerializable("orderDetail", detailBean);
                            bundle.putString("orderId", mPayInfo.orderId);
//                            bundle.putString("in_date", checkInDate);
//                            bundle.putString("out_date", checkOutDate);
//                            bundle.putInt("orderType", mPayInfo.orderType);
                            AndroidUtils.startNextActivity(ConsultOrBookInfoActivity.this, PayOrderActivity.class, bundle, false);
                        }

                        @Override
                        public void onError(@NonNull Throwable e) {
                            e.printStackTrace();            //请求失败
                            dismissLoading();
                        }

                        @Override
                        public void onComplete() {
                            dismissLoading();
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && null != data) {
            if (requestCode == 10101) {
                checkInDate = data.getExtras().getString("check_in");
                checkOutDate = data.getExtras().getString("check_out");

                tvCheckinDate.setText(checkInDate);
                tvCheckoutDate.setText(checkOutDate);
            }
        }
    }
}
